app.controller('UploadFilePanelCtrl', ['$scope', '$element', function ($scope, $element) {
    $scope.uploadButtonName = $element.attr('upload-button-name') || '上传';
    $scope.uploadIframeId = "commonUploadIframe";
    $scope.uploadFormId = $element.attr('upload-form-id') || randomStr(10);
    $scope.onUploaded = $element.attr('on-uploaded') || 'function(){}';
    $scope.beforeUpload = $element.attr('before-upload') || '0';
    $scope.isPublicFile = $element.attr('is-public') === 'true';
    $scope.toUpload = function () {
        try {
            $scope.$parent.$eval($scope.beforeUpload) || $scope.$eval($scope.beforeUpload);
        } catch (e) {
        }
        var jsCallback = "callback_" + randomStr(10);
        var $form = $("#" + $scope.uploadFormId);
        $form[0].reset();
        $form.find('[name=file]').trigger('click');
        $form.find('[name=jsCallback]').val(jsCallback);
        $form.find('[name=parentFolderId]').val('0');
        $form.find('[name=isPublic]').val($scope.isPublicFile);
        $form.attr('action', '/wechatshop/file/upload_using_forms');
        $form.find('[name=originHost]').val(window.location.protocol + '//' + window.location.host);
        $form.find('[name=file]').change(function () {
            $form.submit();
        });
        window[jsCallback] = function (fileId) {
            var f = $scope.$parent.$eval($scope.onUploaded) || $scope.$eval($scope.onUploaded);
            f(fileId);
        };
        window.addEventListener('message', function (event) {
            eval(event.data);
        });
    };
}]).directive('uploadFilePanel', function () {
    return {
        replace: true,
        scope: true,
        controller: 'UploadFilePanelCtrl',
        templateUrl: 'static/js/directives/upload-file-panel.html'
    };
});